package com.example.test.mapper;

import com.example.test.model.Order;
import com.example.test.model.User;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface UserMapper {
    @Insert("INSERT INTO \"user\" (name, username, password, created_at, updated_at) " +
            "VALUES (#{name}, #{username}, #{password}, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP) ")
    @Options(useGeneratedKeys = true, keyProperty = "id", keyColumn = "id")
    void save(User user);

    @Select("SELECT * FROM \"user\" WHERE id = #{id}")
    @Results({
            @Result(property = "createdAt", column = "created_at"),
            @Result(property = "updatedAt", column = "updated_at")
    })
    User findById(long id);

    @Select("SELECT * FROM \"user\" ORDER BY id LIMIT #{limit} OFFSET #{offset}")
    @Results({
            @Result(property = "createdAt", column = "created_at"),
            @Result(property = "updatedAt", column = "updated_at")
    })
    List<User> find(int offset, int limit);

    @Select("SELECT * FROM \"order\" WHERE user_id = #{userId} ORDER BY payment_time DESC LIMIT 10")
    @Results({
            @Result(property = "id", column = "id"),
            @Result(property = "userId", column = "user_id"),
            @Result(property = "productName", column = "product_name"),
            @Result(property = "paymentTime", column = "payment_time"),
            @Result(property = "paymentAmount", column = "payment_amount")
    })
    List<Order> findRecentOrdersByUserId(long userId);

    @Update("UPDATE \"user\" SET name = #{name}, username = #{username}, password = #{password}, updated_at = CURRENT_TIMESTAMP " +
            "WHERE id = #{id}")
    @Options(useGeneratedKeys = true, keyProperty = "id", keyColumn = "id")
    void update(User user);

    @Delete("DELETE FROM \"user\" WHERE id = #{id}")
    void deleteById(long id);
}
